﻿using System;
using Flagwind.ComponentModel;
using Flagwind.Diagnostics;
using Flagwind.Plugins;

namespace Flagwind.Web.Plugins.Diagnostics
{
	public class ExceptionHandlerModule : IApplicationModule, IDisposable
	{
		#region 常量定义

		private const string ROOT_HANDLERS_PATH = "/Workspace/ExceptionHandlers";

		#endregion

		#region 公共属性

		public virtual string Name
		{
			get
			{
				return this.GetType().Name;
			}
		}

		#endregion

		#region 公共方法

		public virtual void Initialize(ApplicationContextBase context)
		{
			if(context == null)
				return;

			var applicationContext = (ApplicationContext)context;
			var handlersNode = applicationContext.PluginContext.PluginTree.Find(ROOT_HANDLERS_PATH);

			if(handlersNode != null)
			{
				foreach(var handlerNode in handlersNode.Children)
				{
					var type = ((Builtin)handlerNode.Value).BuiltinType.Type;

					if(!typeof(IExceptionHandler).IsAssignableFrom(type))
						throw new Options.Configuration.OptionConfigurationException(string.Format("The '{0}' type isn't a IExceptionHandler.", type.FullName));

					var handler = handlerNode.UnwrapValue<IExceptionHandler>(ObtainMode.Auto);

					// 添加异常处理程序。
					ExceptionHandlerManager.Instance.Handlers.Add(handler);
				}
			}
		}

		#endregion

		#region 处置方法

		void IDisposable.Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{

		}

		#endregion
	}
}
